package com.jaydenxiao.common.baserx;

import com.jaydenxiao.common.basebean.BaseRespose;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;
import me.jessyan.autosize.utils.LogUtils;


/**
 * des:对服务器返回数据成功和失败处理
 */

public class RxHelper {

    /** 对服务器返回数据进行预处理 **/
    public static <T> ObservableTransformer<BaseRespose<T>,T> handleFlatMap(){
        return upstream -> upstream
                .flatMap(new Function<BaseRespose<T>, ObservableSource<T>>() {
            @Override
            public ObservableSource<T> apply(BaseRespose<T> tBaseRspose) throws Exception {
                LogUtils.e("请求状态-->"+tBaseRspose.getCode());
                if(tBaseRspose!=null){
                    if(tBaseRspose.getCode()==200){
                        if(tBaseRspose.getMeta()==null){
                            tBaseRspose.setMeta((T) new String(""));
                        }
                        return createData(tBaseRspose.getMeta());
                    }/*else if(tBaseRspose.getCode()==201){
                        return Observable.error(new TokenOffException("201"));
                    }*/
                    else{
                        return Observable.error(new ApiException(tBaseRspose.getCode(),tBaseRspose.getMsg()));
                    }
                }
                return Observable.error(new ApiException(500,"请求失败"));
            }
        }).compose(RxSchedulersThread.io_main()); //调度

    }




    /** 创建成功的数据 **/
    private static <T> Observable<T> createData(final T data) {
        return Observable.create(e -> {
            try {
                e.onNext(data);
                e.onComplete();
            }catch (Exception ex){
                e.onError(ex);
            }
           
        });
    }

}
